#include "ExrFileIO.h"


CExrFileIO::CExrFileIO(void)
{
}


CExrFileIO::~CExrFileIO(void)
{
}

void CExrFileIO::LoadExrFile(char* strFileName)
{
	if(strFileName == NULL)
		 return;

	RgbaInputFile file (strFileName);
	Box2i dw = file.dataWindow();
	m_iImgWidth = dw.max.x - dw.min.x + 1;
	m_iImgHeight = dw.max.y - dw.min.y + 1;
	m_arrPixels.resizeErase (m_iImgWidth, m_iImgHeight);
	file.setFrameBuffer (&m_arrPixels[0][0], 1, m_iImgWidth);
	file.readPixels (dw.min.y, dw.max.y);

}

void CExrFileIO::SaveExrFile(char* strFileName, RgbaChannels iChannels /* = WRITE_RGB */)
{
	if(strFileName == NULL || m_iImgWidth == 0 || m_iImgHeight == 0)
		return;
	RgbaOutputFile outFile(strFileName, m_iImgWidth, m_iImgHeight, iChannels);
	outFile.setFrameBuffer (&m_arrPixels[0][0], 1, m_iImgWidth);
	outFile.writePixels (m_iImgHeight);
}

void CExrFileIO::SaveWarpedExrFile(char* strFileName, TransFormData_2D& trans, RgbaChannels iChannels /* = WRITE_RGB */)
{
	if(strFileName == NULL || m_iImgWidth == 0 || m_iImgHeight == 0)
		return;

	Array2D<Rgba> warpedImg;
	warpedImg.resizeErase(m_iImgWidth,m_iImgHeight);
	
	//start warping
	for( int iY=0; iY < m_iImgHeight; iY++ ) { 
		for( int iX=0; iX < m_iImgWidth; iX++ ) {

			float xPos = iX + trans.m_fTransX + 0.5f;
			float yPos = iY + trans.m_fTransY + 0.5f;

			if(xPos < 0 || yPos < 0 || xPos >= m_iImgWidth || yPos >= m_iImgHeight )
				continue;

			int xIdx = (int)(floorf(xPos));
			int yIdx = (int)(floorf(yPos));

    		*(&warpedImg[0][0] + yIdx*m_iImgWidth + xIdx) = 
				*(&m_arrPixels[0][0] + iY*m_iImgWidth + iX); 
		} //Set red to max (BGR format)
	}

	RgbaOutputFile outFile(strFileName, m_iImgWidth, m_iImgHeight, iChannels);
	//RgbaOutputFile outFile(strFileName, m_iImgWidth, m_iImgHeight, iChannels,1,Imath::V2f(0, 0),1,INCREASING_Y,NO_COMPRESSION);
	outFile.setFrameBuffer (&warpedImg[0][0], 1, m_iImgWidth);
	outFile.writePixels (m_iImgHeight);
}